//
//  WBUserAccount.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/13.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

let jsonName = "useraccount.json"

class WBUserAccount: NSObject {
    /// 访问令牌
    var access_token: String?
    /// 用户代号
    var uid: String?
    /// token使用时限
    var expires_in: TimeInterval = 0 {
        didSet {
            expires = Date(timeIntervalSinceNow: expires_in)
        }
    }
    /// 授权过期时间
    var expires: Date?
    /// 显示名称
    var screen_name: String?
    /// 头像大图
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        // 从磁盘加载保存的文件
        let path = jsonName.az_appendDocumentDir()
        guard let data = NSData(contentsOfFile: path),
        let dict = try? JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as? [String:AnyObject] else {
            return
        }
        
        yy_modelSet(with: dict ?? [:])
        
        if expires?.compare(Date()) == .orderedAscending {
            access_token = nil
            uid = nil
            
            try? FileManager.default.removeItem(atPath: path)
        }
    }
    
    func save() {
        var dic = self.yy_modelToJSONObject() as? [String:AnyObject] ?? [:]
        
        dic.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
             else {
                return
        }

        let filePath = jsonName.az_appendDocumentDir()
        
        (data as NSData).write(toFile: filePath, atomically: true)
        
        debugPrint(filePath)
    }
}
